/*
 * File:ProviderFactory.java Type:net.wangds.common.factory.ProviderFactory
 */

package net.wangds.common.factory;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * Provider的工厂类.
 * <p>
 * <ol>
 * <li>初始版本, by wangds@gmail.com, 2013-10-27 下午6:04:31</li>
 * </ol>
 * </p>
 * 
 * @author wangds@gmail.com
 * @version 0.1.1
 * @since 0.1
 */
public final class ProviderFactory {

  /**
   * 获得Provider.
   * 
   * @param <T>
   *          目标类型
   * @param interfaceclass
   *          目标类型
   * @return 目标实例.
   */
  public static <T> T getInstance(Class<T> interfaceclass) {
    T res = null;
    try {
      ServiceLoader<T> loader = ServiceLoader.load(interfaceclass);
      Iterator<T> it = loader.iterator();
      while (it.hasNext()) {
        res = it.next();
        if (res != null) {
          break;
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return res;
  }

  /**
   * .
   * @author wangds 2016年1月11日 下午7:45:42.
   * @param interfaceclass .
   * @param filter .
   * @return .
   */
  public static <T> T getInstance(Class<T> interfaceclass, Filter<T> filter) {
    T res = null;
    try {
      ServiceLoader<T> loader = ServiceLoader.load(interfaceclass);
      Iterator<T> it = loader.iterator();
      if (filter == null) {
        if (it.hasNext()) {
          res = it.next();
        }
        return res;
      } else {
        T cur = null;
        while (it.hasNext()) {
          cur = it.next();
          if (res == null) {
            res = cur;
          }
          if (filter.accept(cur)) {
            res = cur;
            break;
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return res;
  }

}
